package dk.mirasola.systemtraining.biddingsession.client;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import dk.mirasola.systemtraining.biddingsession.client.ui.BidSessionPanel;
import dk.mirasola.systemtraining.biddingsession.client.ui.CompletedSessionPanel;
import dk.mirasola.systemtraining.biddingsession.client.util.BiddingSessionAsyncCallback;
import dk.mirasola.systemtraining.biddingsession.shared.service.SessionNotFoundException;
import dk.mirasola.systemtraining.biddingsession.shared.service.SessionService;
import dk.mirasola.systemtraining.biddingsession.shared.service.SessionServiceAsync;
import dk.mirasola.systemtraining.biddingsession.shared.transfer.StartSessionTO;

public class BiddingSessionEntryPoint implements EntryPoint {
    private static SessionServiceAsync sessionService = GWT.create(SessionService.class);

    public void onModuleLoad() {
        String sessionId = Window.Location.getParameter("session");

        if (sessionId == null || "".equals(sessionId)) {
            RootPanel.get().add(new Label("No session specified"));
            return;
        }

        sessionService.startSession(sessionId, new BiddingSessionAsyncCallback<StartSessionTO>() {
            public void onFailure(Throwable throwable) {
                try {
                    throw throwable;
                } catch (SessionNotFoundException e) {
                    RootPanel.get().add(new Label("Session not found"));
                } catch (Throwable t) {
                    super.onFailure(t);
                }
            }

            @Override
            public void onSuccess(StartSessionTO res) {
                if (!res.isActive()) {
                    RootPanel.get().add(new Label("Session already completed"));
                } else if (res.isBiddingSetFinish()) {
                    RootPanel.get().add(new CompletedSessionPanel(res.getBiddingSetKey()));
                } else {
                    RootPanel.get().add(new BidSessionPanel(res.getBiddingSetKey()));
                }
            }

        });
    }
}
